
package com.epam.android.training.day13.task2;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import java.util.List;

/**
 * Simple activity that handles geolocation changes and shows current position
 * on the map.
 * 
 * @author Anton Novikau
 */
public class MainActivity extends MapActivity {

  private LocationManager locationManager;

  private MapOverlay overlay;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // get system location manager.
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    // find map view and allow built-in zoom controls
    MapView mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);

    addLocationListener(mapView);
    Drawable itemIcon = getResources().getDrawable(android.R.drawable.star_big_on);

    // create overlay to indicate the current position.
    overlay = new MapOverlay(itemIcon);
  }

  @Override
  protected boolean isRouteDisplayed() {
    return false;
  }

  /**
   * Adds location listener that handeles geolocation changes.
   * 
   * @param mapView {@link MapView} to show the changes on UI
   */
  private void addLocationListener(final MapView mapView) {
    final MapController mapController = mapView.getController();

    final List<Overlay> overlays = mapView.getOverlays();

    LocationListener listener = new LocationListener() {

      @Override
      public void onStatusChanged(String provider, int status, Bundle extras) {}

      @Override
      public void onProviderEnabled(String provider) {}

      @Override
      public void onProviderDisabled(String provider) {}

      @Override
      public void onLocationChanged(Location location) {
        if (location != null) {
          // get current location.
          GeoPoint currentPoint = new GeoPoint((int) (location.getLatitude() * 1E6),
              (int) (location.getLongitude() * 1E6));

          // add new marker with current position.
          overlay.setItem(new OverlayItem(currentPoint, "", ""));
          overlays.add(overlay);

          // move screen to new marker.
          mapController.animateTo(currentPoint);
          mapView.invalidate();
        }
      }
    };

    // assign created listener to location manager.
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
  }
}
